<?php

namespace Beerus\Modules\GoodsTest\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\GoodsTestActivity\FineGoodsContentModel;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Biz\service\wiki\ObjRelateWiki as sObjRelateWiki;
use \Biz\model\wiki\Wiki as mWiki;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;

class DetailReportController extends Controller
{
    const PAGE_SIZE = 20;

    /**
     * 详情页
     * @param \Illuminate\Http\Request $request
     * @param Content $content
     * @param $id
     * @return Content|Application|RedirectResponse|Redirector
     */
    public function index(Request $request, Content $content, $id)
    {
        $list = FineGoodsContentModel::select('*',
            ['fine_goods_id' => $id, 'is_delete[!]' => FineGoodsContentModel::IS_DELETE_TRUE]);
        $list = FineGoodsService::formatNoteList($list);
        $gridModel = new GridDataModel($list);
        Admin::script($this->relatedWikiScript());
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disableCreateButton();
                //显示当前页的序号
                $grid->number('序号');
                $grid->rows(function ($row, $number) {
                    $row->column('number', $number + 1);
                });
                $grid->column('id', 'ID');
                $grid->column('title', '标题');
                $grid->column('obj_id', '内容ID')->copyable();
                $grid->column('nickName', '发布者');
                $grid->column('obj_wiki_info_name_map', '关联商品')->modal('关联商品', function () {
                    $wiki_info = $this->obj_wiki_info;
                    $data = [];
                    if ($wiki_info) {
                        foreach ($wiki_info as $item) {
                            $data[] = [
                                'id' => $item['id'],
                                'basic_id' => $item['basic_id'],
                                'title' => $item['title'],
                                'cover_img' => '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'800px\', \'845px\'],content: \''.$item['cover_img'].'\'});">
                                <img width="100px" height="100px" src="'.$item['cover_img'].'">
                            </a>',
                            ];
                        }
                    }

                    return new Table(['商品ID', 'WIKI ID', '标题', '主图'], $data);
                });
                $grid->column('noteAddtime', 'note发布日期');
                $grid->column('points', '分值');
                $grid->column('link')->newQrcode();
                $grid->column('obj_is_related_wiki','是否已关联当前活动wiki')->bool();
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->prepend(
                        ' <a class="fa related-wiki"  data-id="'.$actions->row->id.' " href="javascript:void(0);">
                                    <span  aria-hidden="true">关联商品</span></a>');
                });
            }
        );
        $tab = new Tab();
        $tab->addLink("活动详情页 ", url("/admin/goodsTest/detail/$id"), false);
        $tab->addLink('获选名单', url("/admin/goodsTest/joinSelected/index/$id"), false);
        $tab->addLink('测评报告管理', url("/admin/goodsTest/reportList/index/$id"), false);
        $tab->add('测评报告', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header('测评报告')
            ->breadcrumb(['text' => '审核列表', 'url' => '/goodsTest/index'], ['text' => '测评报告']);
    }


    /**
     * @return string
     */
    private function relatedWikiScript(): string
    {
        return <<<SCRIPT
        $('.related-wiki').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/goodsTest/detail/report/relatedWiki'
            let params = {id:id}
            swal({
                    title: "确认要关联商品吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function relatedWiki(Request $request): JsonResponse
    {
        $id = $request->input('id', '');
        $message = [
            'title' => '操作成功',
            'code' => 1,
        ];
        if ($id) {
            $info = FineGoodsContentModel::first(['id' => $id]);
            $basicId = $info['basic_id'] ?? 0;
            $noteId = $info['obj_id'] ?? 0;

            if ($basicId) {
                $wikiId = mWiki::getInfoByBasicId($basicId,'id');
                try {
                    sObjRelateWiki::admNoteRelate($noteId, '', Admin::user()->id, $wikiId);
                } catch (Exception $e) {
                    Log::error('error', $e->getMessage());
                    $message = [
                        'title' => '操作失败,'.$e->getMessage(),
                        'msg' => '信息：'.$e->getFile().$e->getLine(),
                        'code' => 0,
                        'status' => false,
                    ];
                }
            }
        }

        return response()->json($message);
    }
}
